package indexes;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import trees.BPlusTree;
import util.BattingBPlusConverter;
import util.BattingBPlusRecord;
import util.PlayerLogger;
/**
 * This class provides an interface to the index structure housing
 * the relationship between a player id and their batting records
 * within the batting database.
 * @author xclite
 *
 */
public class BattingIndex
{
    private BPlusTree<String, Long, BattingBPlusRecord> bTree;
    
    /**
     * Creates the tree with the given parameters. 
     * @param logger
     * @param m
     * @throws FileNotFoundException
     */
    public BattingIndex(PlayerLogger logger, int m) throws FileNotFoundException
    {
        this.bTree = new BPlusTree<String, Long, BattingBPlusRecord>(m, new BattingBPlusConverter(), logger);
    }
    
    
    
    /**
     * Adds the record to the tree.
     * TODO: Duplicates?  I don't think so.
     * @param record 
     * @throws IOException 
     */
    public void add(BattingBPlusRecord record) throws IOException
    {
        bTree.insert(record);
    }


    /**
     * A player name may have several offsets, so we give back
     * a list of offsets for the given player.
     * @param key1 beginning of range to traverse
     * @param key2 end of range to traverse.
     * @return Null if the player name is not found, a list
     * of file offsets otherwise.
     * @throws IOException 
     */
    public List<Long> getRange(String key1, String key2 ) throws IOException
    {
        return bTree.getRange(key1, key2);
    }

    /**
     * Removes the id from the tree.
     * @param key the key to search for
     * @throws IOException 
     * @throws IOException 
     */
    public void remove(String key) throws IOException
    {
       bTree.remove(new BattingBPlusRecord(key, new Long(-1)));
    }
    
    /**
     * Attempts to find the key within the index.
     * @param key
     * @return the offset within the batting database for the key, null if not found.
     * @throws IOException
     */
    public Long search(String key) throws IOException
    {
        return bTree.search(key);
    }
    
    /**
     * Writes a representation of the index to the log
     * file.
     * @throws IOException
     */
    public void logIndex() throws IOException
    {
        bTree.logTree();
    }
}
